<template>
  <div class="bg-settings">
    <el-form
      :model="shopDataForm"
      ref="shopDataForm"
      :rules="rules"
      label-width="200px"
      class="demo-ruleForm"
      status-icon>
      <!--店铺名称-->
      <el-form-item label="店铺名称：" prop="shop_name">
        <el-input v-model="shopDataForm.shop_name" @change="() => { shopDataForm.shop_name = shopDataForm.shop_name.trim() }" style="width: 200px;" auto-complete="off"></el-input>
      </el-form-item>
      <!--身份证号-->
      <el-form-item label="身份证号：" prop="legal_id">
        <span>{{ shopDataForm.legal_id }}</span>
      </el-form-item>
      <!--店铺地址-->
      <el-form-item label="店铺地址：" prop="shop_region">
        <en-region-picker :api="MixinRegionApi" :default="areas" @changed="(object) => { shopDataForm.shop_region = object.last_id }"></en-region-picker>
      </el-form-item>
      <!--详细地址-->
      <el-form-item label="详细地址：" prop="shop_add">
        <el-input v-model="shopDataForm.shop_add" @change="() => { shopDataForm.shop_add = shopDataForm.shop_add.trim() }"  style="width: 200px;" auto-complete="off"></el-input>
      </el-form-item>
      <!--详细地址-->
      <el-form-item label="地图点位：" prop="shop_map">
        <div class="map">
          <div id="mapContainer" style="height: 400px"></div>
          <input type="text" id="mapInput" class="map-search" placeholder="请输入店铺地址" />
        </div>
      </el-form-item>
      <!--联系电话-->
      <el-form-item label="联系电话：" prop="link_phone">
        <el-input v-model="shopDataForm.link_phone" style="width: 200px;" maxLength="11"></el-input>
      </el-form-item>
      <!--QQ-->
      <el-form-item label="QQ：" prop="shop_qq">
        <el-input v-model="shopDataForm.shop_qq" style="width: 200px;" placeholder="请设置店铺的客服QQ"></el-input>
        <span class="QQ-tip">（设置店铺的客服QQ）</span>
      </el-form-item>
      <!--店铺简介-->
      <el-form-item label="店铺简介：" prop="shop_desc">
        <UE ref="UE" :defaultMsg="shopDataForm.shop_desc" style="width: 80%;"></UE>
      </el-form-item>
      <!--店铺logo-->
      <el-form-item label="店铺logo：" prop="shop_logo">
        <el-upload
          class="upload-demo"
          key="shop_logo"
          :action="`${MixinUploadApi}?scene=shop`"
          :on-success="uploadSuccessLogo"
          :before-upload="handleImagesUrlBefore"
          :file-list="fileList_logo"
          ref="fileList_logo"
          list-type="picture">
          <el-button size="small" type="primary">
            上传<i class="el-icon-upload el-icon--right"></i>
          </el-button>
          <div slot="tip" class="el-upload__tip">
            此处为您的店铺logo，将显示在店铺Logo栏里。 （限制上传宽高比例为1:1的图片！）
          </div>
        </el-upload>
      </el-form-item>
      <!--营业时间-->
      <el-form-item class="open_tim_row" label="营业时间：" required>
        <el-form-item prop="open_time_type">
          <el-radio-group v-model="shopDataForm.open_time_type">
            <el-radio :label="1">全天</el-radio>
            <el-radio :label="2">自定义</el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="radio-selct" v-if="shopDataForm.open_time_type===2">
          <div class="open_time_line">
            <el-form
              :model="item"
              :rules="openTimeRule"
              ref="openTimeForm"
              label-width="200px"
              v-for="(item, index) in openTimeArr" :key="index">
              <el-form-item prop="start_time" :rules="{ required: true, message: '请输入开始时间', trigger: 'blur' }">
                <el-time-select
                  class="w120"
                  arrow-control
                  placeholder="开始时间"
                  v-model="item.start_time"
                  :picker-options="{
                    start: '00:00',
                    step: '00:15',
                    end: '23:45',
                    maxTime: item.end_time
                  }">
                </el-time-select>
              </el-form-item>
              <span class="unit-tip">至</span>
              <el-form-item prop="end_time" :rules="{ required: true, message: '请输入结束时间', trigger: 'blur' }">
                <el-time-select
                  class="w120"
                  arrow-control
                  placeholder="结束时间"
                  v-model="item.end_time"
                  :picker-options="{
                    start: '00:00',
                    step: '00:15',
                    end: '23:45',
                    minTime: item.start_time
                  }">
                </el-time-select>
              </el-form-item>
              <el-button type="text" class="add_open_time" v-if="shopDataForm.open_time_type===2 && index===0" size="medium" @click="addOpenTime()">添加时间段</el-button>
              <el-button type="text" class="add_open_time" v-if="shopDataForm.open_time_type===2 && index>0" size="medium" @click="delOpenTime(index)">删除</el-button>
            </el-form>
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSaveShopData('shopDataForm')">保存修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import AMap from 'AMap'
  import * as API_Shop from '@/api/shop'
  import { UE } from '@/components'
  import { RegExp } from '~/ui-utils'
  let map = null // 地图
  let marker = null // 自定义标记点
  let useLnglat = null // 当前经纬度
  export default {
    name: 'shopSetting',
    components: {
      [UE.name]: UE
    },
    data() {
      const validPhone = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入联系人电话'))
        } else if (!RegExp.mobile.test(value)) {
          callback(new Error('请输入正确的11位手机号码'))
        } else {
          callback()
        }
      }
      const validQQ = (rule, value, callback) => {
        if (value && !/^[0-9]\d*$/g.test(value)) {
          callback(new Error('请输入0-9之间的整数'))
        } else {
          callback()
        }
      }
      return {
        /** 店铺信息*/
        shopDataForm: {
          /** 店铺ID */
          shop_id: 0,

          /** 店铺名称 */
          shop_name: '',

          /** 身份证号*/
          legal_id: '',

          /** 店铺地址id */
          shop_region: '',

          /** 详细地址*/
          shop_add: '',

          /** 联系电话*/
          link_phone: '',

          /** QQ*/
          shop_qq: '',

          /** 店铺简介*/
          shop_desc: '',

          /** 店铺logo*/
          shop_logo: ''
        },
        
        /** 添加时间段*/
        openTimeArr: [{
          start_time: '',
          end_time: ''
        }],

        openTimeRule: {
          /** 营业时间 */
          start_time: [
            { required: true, message: '请选择开始时间', trigger: 'change' }
          ],

          /** 营业时间 */
          end_time: [
            { required: true, message: '请选择结束时间', trigger: 'change' }
          ]
        },

        /** 地区信息*/
        areas: [],

        /** 店铺logo图片存*/
        fileList_logo: [],

        /** 店铺banner图片存*/
        fileList_banner: [],

        /** 校验规则 校验必填 */
        rules: {
          /** 店铺名称 */
          shop_name: [
            { required: true, message: '请填写店铺名称', trigger: 'blur' },
            { whitespace: true, message: '店铺名称不可为纯空格', trigger: 'blur' },
            { max: 15, message: '店铺名称长度最多15个字符', trigger: 'blur' }
          ],

          /** 店铺地址 */
          shop_region: [
            { required: true, message: '请填写店铺地址', trigger: 'blur' }
          ],

          /** 详细地址 */
          shop_add: [
            { required: true, message: '详细地址不可为纯空格', trigger: 'blur' },
            { max: 50, message: '详细地址长度最多50个字符', trigger: 'blur' }
          ],

          /** 地图点位 */
          shop_map: [
            { required: true, message: '请设置有效的地图点位', trigger: 'blur' }
          ],

          /** 联系人电话 */
          link_phone: [
            { required: true, message: '请填写联系人电话', trigger: 'blur' },
            { validator: validPhone, trigger: 'blur' }
          ],

          /** 店铺qq */
          shop_qq: [
            { required: false, trigger: 'change', validator: validQQ },
            { max: 20, message: '店铺QQ长度最多20个字符', trigger: 'change' }
          ],

          /** 店铺logo */
          shop_logo: [
            { required: true, message: '请上传店铺logo', trigger: 'change' }
          ],

          /** 营业时间 */
          open_time_type: [
            { required: true, message: '请选择营业时间', trigger: 'change' }
          ],

          /** 营业时间 */
          open_start_time: [
            { required: true, message: '请选择开始时间', trigger: 'change' }
          ],

          /** 营业时间 */
          open_end_time: [
            { required: true, message: '请选择结束时间', trigger: 'change' }
          ]
        }
      }
    },
    mounted() {
      this.GET_ShopGradeData()
    },
    methods: {
      /** 获取店铺信息 */
      GET_ShopGradeData() {
        API_Shop.getShopData().then(async response => {
          await this.initMap() // 初始化地图
          this.shopDataForm = { ...response }
          this.fileList_logo = [{ url: this.shopDataForm.shop_logo }]
          this.areas = [
            this.shopDataForm.shop_province_id,
            this.shopDataForm.shop_city_id,
            this.shopDataForm.shop_county_id || -1,
            this.shopDataForm.shop_town_id || -1
          ]
          let _shop_map = []
          const _lng = response.shop_lng
          const _lat = response.shop_lat
          if (_lng || _lat) {
            let _position = new AMap.LngLat(_lng, _lat)
            this.showMapMarker(_position)
            _shop_map = [_lng, _lat]
          }
          this.shopDataForm.shop_map = _shop_map
          this.openTimeArr = response.open_time? JSON.parse(response.open_time): this.openTimeArr
          this.$nextTick(() => {
            this.$refs.shopDataForm.clearValidate()
          })
          this.initAutocomplete()
        })
      },

      /*
        * @date 2020-02-16
        * @author wolfMan
        * @description {初始化地图}
      */
      initMap() {
        // 初始化地图
        map = new AMap.Map('mapContainer', {
          resizeEnable: true,
          zoom: 16
        })
        // 生成自定义标记点
        marker = new AMap.Marker({
          position: map.getCenter(),
          cursor: 'move',
          raiseOnDrag: true, // 标记点拖拽
          offset: new AMap.Pixel(-13, -30) // 以 icon 的 [center bottom] 为原点
        })
        // 生成地图内自动填充输入框
        const placeSearch = new AMap.PlaceSearch({ map: map })
        marker.setMap(map)
        // map点击事件生成自定义标记点
        map.on('click', (e) => {
          this.setAddress(e.lnglat)
          marker.setPosition(e.lnglat)
        })
        // 点击标记点选择地址
        placeSearch.on('markerClick', (e) => {
          this.setAddress(e.event.lnglat)
        })
        // 添加插件到map上
        AMap.plugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.PlaceSearch'], function() {
          map.addControl(new AMap.PlaceSearch())
          map.addControl(new AMap.ToolBar())
          map.addControl(new AMap.Scale())
        })
      },
      /*
        * @date 2020-02-16
        * @author wolfMan
        * @description {设置地图标点}
      */
      showMapMarker(_lnglat) {
        map.setCenter(_lnglat)
        marker.setPosition(_lnglat)
      },
      /*
        * @date 2020-02-16
        * @author wolfMan
        * @description {自动填充地址}
      */
      setAddress(lnglat) {
        const geocoder = new AMap.Geocoder()
        geocoder.getAddress(lnglat, (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            const {
              regeocode: {
                formattedAddress,
                addressComponent: { province, city, district }
              }
            } = result
            if (!this.shopDataForm.shop_add || this.shopDataForm.shop_add.trim() === '') {
              this.$set(this.shopDataForm, 'shop_add', formattedAddress)
            }
            this.$set(this.shopDataForm, 'shop_lng', lnglat.lng)
            this.$set(this.shopDataForm, 'shop_lat', lnglat.lat)
            this.$set(this.shopDataForm, 'shop_map', [lnglat.lng, lnglat.lat])
          }
        })
      },
      /*
        * @date 2019-12-06
        * @author wolfMan
        * @description {自动匹配地址选项}
      */
      initAutocomplete() {
        const mapAutoComplete = new AMap.Autocomplete({ input: 'mapInput' })
        mapAutoComplete.on('select', (res) => {
          if (res.poi.location) {
            const _location = res.poi.location
            this.setAddress(_location)
            let _position = new AMap.LngLat(_location.lng, _location.lat)
            this.showMapMarker(_position)
          } else {
            this.$message.warning('您选择的地址不是一个具体的地址')
          }
        })
      },
      /* 添加营业时间段 */
      addOpenTime() {
        let timeArrLength = this.openTimeArr.length
        let arg = {
          start_time: '',
          end_time: ''
        }
        this.$set(this.openTimeArr, timeArrLength, arg)
      },
      /* 删除营业时间段 */
      delOpenTime(index) {
        this.openTimeArr.splice(index, 1)
      },
      /** 保存店铺设置*/
      handleSaveShopData(formName) {
        this.shopDataForm.shop_desc = this.$refs['UE'].getUEContent()
        let openTimeFlag = true
        this.openTimeArr.forEach((item, index) => {
          if (this.$refs.openTimeForm&&this.$refs.openTimeForm.length) {
            this.$refs.openTimeForm[index].validate((valid) => {
              if (!valid) {
                openTimeFlag = false
              }
            })
          }
        })
        this.$refs[formName].validate((valid) => {
          if (valid&&openTimeFlag) {
            const _params = {
              shop_add: this.shopDataForm.shop_add,

              shop_lat: this.shopDataForm.shop_lat,

              shop_lng: this.shopDataForm.shop_lng,

              shop_name: this.shopDataForm.shop_name,

              link_phone: this.shopDataForm.link_phone,

              shop_logo: this.shopDataForm.shop_logo,

              shop_desc: this.shopDataForm.shop_desc || '',

              shop_qq: this.shopDataForm.shop_qq,

              shop_region: this.shopDataForm.shop_region,

              open_time_type: this.shopDataForm.open_time_type,

              // open_start_time: this.shopDataForm.open_start_time,

              // open_end_time: this.shopDataForm.open_end_time
              open_time: JSON.stringify(this.openTimeArr)
            }
            API_Shop.saveShopSettings(_params).then(() => {
              this.$message.success('保存店铺设置成功')
              this.GET_ShopGradeData()
            })
          }
        })
      },

      /** 图片上传之前的校验 */
      handleImagesUrlBefore(file) {
        const isImage = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
        if (!isImage) {
          this.$message.error('上传头像图片只能是 JPG、JPEG或PNG格式!')
          return isImage
        }
        return new Promise((resolve, reject) => {
          let reader = new FileReader()
          reader.onload = (event) => {
            let image = new Image()
            image.onload = () => {
              let width = image.width
              let height = image.height
              if (width !== height) {
                this.$message.error('图片宽高比例必须为1:1！')
                reject()
              }
              resolve()
            }
            image.src = event.target.result
          }
          reader.readAsDataURL(file)
        })
      },

      /** 上传logo成功以后*/
      uploadSuccessLogo(response) {
        this.fileList_logo.shift()
        this.fileList_logo.push(response)
        this.shopDataForm.shop_logo = response.url
      }
    }
  }
</script>

<style lang="scss" type="text/scss" scoped>
  .w120 {
    width: 120px !important;
  }
  .bg-settings {
    background: #fff;
    border: 1px solid #FAFAFA;
    margin: 15px;
    padding: 10px;
  }
  /deep/ .app-address {
    height: 32px;
    min-width: 200px;
    .app-address-title {
      padding: 0 20px 0 15px;
      height: 32px;
      line-height: 32px;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      box-sizing: border-box;
      color: #606266;
    }
  }
  /deep/ .el-form-item--medium .el-form-item__content,
  .el-form-item--medium .el-form-item__label {
    line-height: 24px;
  }
  /deep/ .map {
    position: relative;
    width: 500px;
    .map-search {
      position: absolute;
      top: 15px;
      right: 15px;
      padding: 5px 10px;
      width: 300px;
      line-height: 22px;
      border: none;
      border-radius: 4px;
      outline: none;
      box-shadow: 0 2px 2px rgba(0, 0, 0, .15);
      overflow: hidden;
    }
  }
  /deep/ .upload-demo {
    width: 80%;
    .el-upload-list__item {
      margin-right: 0;
      padding-left: 80px;
      width: 92px;
      .el-upload-list__item-thumbnail {
        margin-left: -70px;
      }
      .el-upload-list__item-thumbnail {
        z-index: 0;
      }
    }
  }
  .QQ-tip {
    font-size: 13px;
    color: #796a6a;
  }
  /deep/ .open_tim_row {
    .add_open_time {
      vertical-align: top;
    }
    .open_time_line {
      .el-form {
        margin-bottom: 15px;
      }
      .el-form-item__content {
        margin: 0!important;
      }
    }
    .el-form-item__content {
      .el-form-item {
        display: inline-block;
        vertical-align: top;
        margin-bottom: 0;
      }
      .radio-selct {
        display: inline-block;
        vertical-align: middle;
        margin-left: 10px;
        .unit-tip {
          display: inline-block;
          vertical-align: middle;
          margin: 0 8px;
          color: #796a6a;
        }
      }
    }
  }
</style>
